PHP - tutorial - 09 - file handling

revision:


PHP - "include" statement - "require" statement

These statements take all the text/code/markup that exists in the specified file and copies it into the file that uses the include/require statement.

The "include" and "require" statements are identical, except upon failure:

"require" will produce a fatal error (E_COMPILE_ERROR) and stop the script.
"include" will only produce a warning (E_WARNING) and the script will continue.

Use "require" when the file is required by the application. Use "include" when the file is not required and application should continue when file is not found.

Syntax: include 'filename'; | require 'filename';

examples

example 1

Welcome to my home page!

Some text.

Some more text.

Copyright © 1999-2025 - www.lwitters.com

code:
                <div class="spec one">
                    <h4>Welcome to my home page!</h4>
                    <p>Some text.</p>
                    <p>Some more text.</p>
                    <?php include 'footer.php';?>
                </div>
                <style>
                    .one{width: 30vw; height: 15vw; background-color: skyblue;}
                </style>
            

example 2

Welcome to my home page!

Some text.

Some more text.

code:
                <div class="spec two">
                    <div class="menu">
                        <?php include 'menu.php';?>
                    </div>
                    <h4>Welcome to my home page!</h4>
                    <p>Some text.</p>
                    <p>Some more text.</p>   
                </div>
                <style>
                    .two{width: 30vw; height: 15vw; background-color: skyblue;}
                </style>
            

example 3

Welcome to my home page!

I have a red BMW.
code:
                <div class="spec three">
                    <h4>Welcome to my home page!</h4>
                    <?php include 'vars.php';
                    echo "I have a $color $car.";
                    ?>
                </div>
                <style>
                    .three{width: 30vw; height: 15vw; background-color: skyblue;}
                </style>
            

PHP - filesystem functions

basename(path, suffix) - returns the filename component of a path.

parameter values:

path : required; specifies a file path;

suffix : optional; a file extension

chgrp(file, group) - changes the file group.

parameter values:

file : required; specifies the path to the file to change user group for;

group : required; specifies the new group name or number

chmod(file, mode) - changes the file mode.

parameter values:

file : required; specifies the path to the file;

mode : required. specifies the new permissions; consists of four numbers: the first number is always zero; the second number specifies permissions for the owner; the third number specifies permissions for the owner's user group; the fourth number specifies permissions for everybody else. Possible values (to set multiple permissions, add up the following numbers): 1 = execute permissions; 2 = write permissions; 4 = read permissions.

chown(file, owner) - changes the file owner

parameter values:

file : required; specifies the path to the file to change owner for;

owner : required; specifies the new owner; can be a user name or a user ID.

clearstatcache(clear_realpath_cache, filename) - clears the file status cache.

parameter values:

clear_realpath_cache : optional; indicates whether to clear the realpath cache or not; default is FALSE, which indicates not to clear realpath cache;

filename : optional; specifies a filename, and clears the realpath and cache for that file only.

copy(from_file, to_file, context) - copies a file.

parameter values:

from_file : required; specifies the path to the file to copy from;

to_file : required; specifies the path to the file to copy to;

context : optional; specifies a context resource created with stream_context_create().

delete() - see unlink().

There is no delete() function in PHP. If you need to delete a file, look at the unlink() function.

dirname(path, levels) - returns the directory name component of a path.

parameter values:

path : required; specifies a path to check;

levels : optional. An integer that specifies the number of parent directories to go up. Default is 1

disk_free_space(directory) - returns the free space of a filesystem or disk.

parameter values:

directory : required; specifies the filesystem or disk to check;

disk_total_space(directory) - returns the total size of a filesystem or disk.

parameter values:

directory : required; specifies the filesystem or disk to check;

diskfreespace() - alias of disk_free_space().

The diskfreespace() function is an alias of the disk_free_space() function.

fclose(filepointer) - closes an open file.

parameter values:

filepointer : required; specifies the file to close;

feof(file) - checks if the "end-of-file" (EOF) has been reached for an open file.

parameter values:

file : required; specifies an open file to check;

fflush(file) - flushes buffered output to an open file.

parameter values:

file : required; specifies the open file to write the buffered output to;

fgetc(file) - returns a single character from an open file.

parameter values:

file : required; specifies the open file to return a single character from;

fgetcsv(file, length, separator, enclosure) - returns a line from an open CSV file.

parameter values:

file : required; specifies the open file to return and parse a line from;

length : optional; specifies the maximum length of a line; must be greater than the longest line (in characters) in the CSV file; omitting this parameter (or setting it to 0) the line length is not limited, which is slightly slower. Note: This parameter is required in versions prior to PHP 5 ;

separator : optional; specifies the field separator; default is comma ( , );

enclosure : optional; specifies the field enclosure character; default is ";

escape : optional; specifies the escape character; default is "\\"

fgets(file, length) - returns a line from an open file.

parameter values:

file : required; specifies the open file to return a line from;

length : optional; specifies the number of bytes to read; reading stops when length-1 bytes have been reached, or when a new line occurs, or on EOF; if no length is specified, it reads until end of the line

fgetss() - deprecated from PHP 7.3. returns a line from an open file - stripped from HTML and PHP tags.

file(filename, flag, context) - reads a file into an array.

parameter values:

filename : required; specifies the path to the file to read;

flags : optional; can be one or more of the flags constants:FILE_USE_INCLUDE_PATH - search for the file in the include_path (in php.ini), FILE_IGNORE_NEW_LINES - Skip the newline at the end of each array element, FILE_SKIP_EMPTY_LINES - skip empty lines in the file;

context : optional; specifies the context of the file handle; context is a set of options that can modify the behavior of a stream; can be skipped by using NULL.

file_exists(path) - checks whether or not a file or directory exists.

parameter values:

path : required. Specifies the path to the file or directory to check;

file_get_contents(path, include_path, context, start, max_length) - reads a file into a string.

parameter values:

path : required; specifies the path to the file to read;

include_path : optional; set this parameter to '1' if you want to search for the file in the include_path (in php.ini) as well;

context : optional; specifies the context of the file handle; context is a set of options that can modify the behavior of a stream; can be skipped by using NULL.;

start : optional; specifies where in the file to start reading; negative values count from the end of the file;

max_length : optional; specifies the maximum length of data read; default is read to EOF

file_put_contents(filename, data, mode, context) - writes data to a file.

parameter values:

filename : required; specifies the path to the file to write to; if the file does not exist, this function will create one;

data : required; the data to write to the file; can be a string, array, or a data stream;

mode : optional; specifies how to open/write to the file; possible values: FILE_USE_INCLUDE_PATH - search for filename in the include directory, FILE_APPEND - if file already exists, append the data to it - instead of overwriting it, LOCK_EX - Put an exclusive lock on the file while writing to it.

context : optional; specifies the context of the file handle; context is a set of options that can modify the behavior of a stream.

fileatime(filename) - returns the last access time of a file.

parameter values:

filename : required; specifies the path to the file to check;

filectime(filename) - returns the last change time of a file.

parameter values:

filename : required; specifies the path to the file to check;

filegroup(filename) - returns the group ID of a file.

parameter values:

filename : required; specifies the path to the file to check;

fileinode(filename) - returns the inode number of a file.

parameter values:

filename : required; specifies the path to the file to check;

filemtime(filename) - returns the last modification time of a file.

parameter values:

filename : required; specifies the path to the file to check;

fileowner(filename) - returns the user ID (owner) of a file.

parameter values:

filename : required; specifies the path to the file to check;

fileperms(filename) - returns the file's permissions.

parameter values:

filename : required; specifies the path to the file to check;

filesize(filename) - returns the file size.

parameter values:

filename : required; specifies the path to the file to check;

filetype(filename) - returns the file type.

parameter values:

filename : required; specifies the file to check;

flock(file, lock, block) - locks or releases a file.

parameter values:

file : required; specifies an open file to lock or release;

lock : required; specifies what kind of lock to use; possible values: LOCK_SH - A shared lock (reader). Allow other processes to access the file, LOCK_EX - An exclusive lock (writer). Prevent other processes from accessing the file, LOCK_UN - Release the lock, LOCK_NB - Avoid blocking other processes while locking

block : optional; set to 1 to block other processes while locking.

fnmatch(pattern, string, flags) - matches a filename or string against a specified pattern.

parameter values:

pattern : required; specifies the shell wildcard pattern;

string : required; specifies the string or file to check;

flags : optional; can be one or a combination of the following: FNM_NOESCAPE - disable backslash escaping, FNM_PATHNAME - slash in string only matches slash in the given pattern, FNM_PERIOD - leading period in string must be exactly matched by period in pattern, FNM_CASEFOLD - caseless match; part of the GNU extension

fopen(filename, mode, include_path, context) - opens a file or URL.

parameter values:

filename : required; specifies the file or URL to open;

mode : required; specifies the type of access you require to the file/stream; possible values:

"r" - Read only. Starts at the beginning of the file.
"r+" - Read/Write. Starts at the beginning of the file.
"w+" - Read/Write. Opens and truncates the file; or creates a new file if it doesn't exist. Place file pointer at the beginning of the file.
"a" - Write only. Opens and writes to the end of the file or creates a new file if it doesn't exist.
"a+" - Read/Write. Preserves file content by writing to the end of the file.
"x" - Write only. Creates a new file. Returns FALSE and an error if file already exists.
"x+" - Read/Write. Creates a new file. Returns FALSE and an error if file already exists.
"c" - Write only. Opens the file; or creates a new file if it doesn't exist. Place file pointer at the beginning of the file.
"c+" - Read/Write. Opens the file; or creates a new file if it doesn't exist. Place file pointer at the beginning of the file.
"e" - Only available in PHP compiled on POSIX.1-2008 conform systems. ;

include_path : optional; set this parameter to '1' if you want to search for the file in the include_path (in php.ini) as well;

context : optional; specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream

fpassthru(file) - reads from the current position in a file - until EOF, and writes the result to the output buffer.

parameter values:

file : required; specifies the open file to read from;

fputcsv((file, fields, separator, enclosure, escape) - formats a line as CSV and writes it to an open file.

parameter values:

file : required; specifies the open file to write to;

fields : required; specifies which array to get the data from;

separator : optional; a character that specifies the field separator; default is comma ( , );

enclosure : optional; a character that specifies the field enclosure character; default is ";

escape : optional; specifies the escape character; default is "\\"; can also be an empty string ("") which disables the escape mechanism

fputs() - alias of fwrite().

fread(file, length) - reads from an open file (binary-safe).

parameter values:

file : required; specifies the open file to read from;

length : required; specifies the maximum number of bytes to read

fscanf(file, format, mixed) - parses input from an open file according to a specified format.

parameter values:

file : required; specifies the file to check ;

format : required; specifies the format; possible format values:

%% - Returns a percent sign.
%b - Binary number.
%c - The character according to the ASCII value.
%d - Signed decimal number.
%e - Scientific notation (e.g. 1.2e+2).
%u - Unsigned decimal number.
%f - Floating-point number (local settings aware) .
%F - Floating-point number (not local settings aware).
%o - Octal number.
%s - String.
%x - Hexadecimal number (lowercase letters).
%X - Hexadecimal number (uppercase letters).

Additional format values. These are placed between the % and the letter (example %.2f):

+ (Forces both + and - in front of numbers. By default, only negative numbers are marked).
' (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %'x20s (this uses "x" as padding).
- (Left-justifies the variable value)[0-9] (Specifies the minimum width held of to the variable value).
.[0-9] (Specifies the number of decimal digits or maximum string length).
Note: If multiple additional format values are used, they must be in the same order as above.

mixed : optional.

fseek(file, offset, whence) - seeks in an open file.

parameter values:

file : required; specifies the open file to seek in;

offset : required; specifies the new position (measured in bytes from the beginning of the file);

whence : optional; possible values: SEEK_SET - Set position equal to offset; default; SEEK_CUR - Set position to current location plus offset; SEEK_END - Set position to EOF plus offset (to move to a position before EOF, the offset must be a negative value)

fstat(file) - returns information about an open file.

parameter values:

file : required; specifies the open file to check;

ftell(file) - returns the current position in an open file.

parameter values:

file : required; specifies the open file to check;

ftruncate(file, size) - truncates an open file to a specified length.

parameter values:

file : required; specifies the open file to truncate;

size : required; specifies the new file size/p>

fwrite(file, string, length) - writes to an open file (binary-safe).

parameter values:

file : required; specifies the open file to write to ;

string : required; specifies the string to write to the open file;

length : optional; specifies the maximum number of bytes to write

glob(pattern, flags) - returns an array of filenames / directories matching a specified pattern.

parameter values:

pattern : required; specifies the pattern to search for;

flags : optional; specifies special settings; possible values:GLOB_MARK - Adds a slash to each item returned, GLOB_NOSORT - Return files as they appear in the directory (unsorted), GLOB_NOCHECK - Returns the search pattern if no match were found, GLOB_NOESCAPE - Backslashes do not quote metacharacters, GLOB_BRACE - Expands {a,b,c} to match 'a', 'b', or 'c', GLOB_ONLYDIR - Return only directories which match the pattern, GLOB_ERR - (added in PHP 5.1) Stop on errors (errors are ignored by default).

is_dir(file) - checks whether a file is a directory.

parameter values:

file : required; specifies the path to the file to check;

is_executable(file) - checks whether a file is executable.

parameter values:

file : required; specifies the path to the file to check;

is_file(file) - checks whether a file is a regular file.

parameter values:

file : required; specifies the path to the file to check;

is_link(file) - checks whether a file is a link.

parameter values:

file : required; specifies the path to the file to check;

is_readable(file) - checks whether a file is readable.

parameter values:

file : required; specifies the path to the file to check;

is_uploaded_file(file) - checks whether a file was uploaded via HTTP POST.

parameter values:

file : required; specifies the path to the file to check;

is_writable(file) - checks whether a file is writable

parameter values:

file : required; specifies the path to the file to check;

is_writeable() - alias of is_writable().

lchgrp(file, group) - changes the group ownership of a symbolic link.

parameter values:

file : required; specifies the path to the file to check;

group : required; specifies the new group by name or number;

lchown(file, group) - changes the user ownership of a symbolic link.

parameter values:

file : required; specifies the path to the symlink;

group : required; specifies the new user by name or number;

link(target, link) - creates a hard link.

parameter values:

target : required; specifies the target;

link : required; specifies the name of the link

linkinfo(path) - returns information about a hard link.

parameter values:

path : required; specifies the path to check;

lstat(filename) - returns information about a file or symbolic link.

parameter values:

filename : required; specifies the path to the file or a symbolic link to check;

mkdir(path, mode, recursive, context) - creates a directory.

parameter values:

path : required; specifies the directory path to create;

mode : optional; specifies permissions; by default, the mode is 0777 (widest possible access); Note: The mode parameters is ignored on Windows platforms!; the mode parameter consists of four numbers: the first number is always zero, the second number specifies permissions for the owner, the third number specifies permissions for the owner's user group, the fourth number specifies permissions for everybody else; possible values (to set multiple permissions, add up the following numbers): 1 = execute permissions, 2 = write permissions, 4 = read permissions ;

recursive : optional; specifies if the recursive mode is set (added in PHP 5);

context : optional; specifies the context of the file handle; context is a set of options that can modify the behavior of a stream (added in PHP 5)

move_uploaded_file(file, dest) - moves an uploaded file to a new location.

parameter values:

file : required; specifies the filename of the uploaded file;

dest : required; specifies the new location for the file.

parse_ini_file(file, process_sections, scanner_mode) - parses a configuration file.

parameter values:

file : required; specifies the ini file to parse;

process_sections : optional; if set to TRUE, it returns a multidimensional array with section names and settings included; default is FALSE;

scanner_mode : optional; can be one of the following values: INI_SCANNER_NORMAL (default), INI_SCANNER_RAW (means option values will not be parsed), INI_SCANNER_TYPED (means that boolean, null and integer types are preserved when possible. "true", "on", "yes" are converted to TRUE. "false", "off", "no", "none" are converted to FALSE. "null" is converted to NULL. Numeric strings are converted to integer type if possible)

parse_ini_string(ini, process_sections, scanner_mode) - parses a configuration file.

parameter values:

ini : required; specifies the ini file to parse;

process_sections : optional; if set to TRUE, it returns a multidimensional array with section names and settings included; default is FALSE;

scanner_mode : optional; can be one of the following values: INI_SCANNER_NORMAL (default), INI_SCANNER_RAW (means option values will not be parsed), INI_SCANNER_TYPED (means that boolean, null and integer types are preserved when possible. "true", "on", "yes" are converted to TRUE. "false", "off", "no", "none" are converted to FALSE. "null" is converted to NULL. Numeric strings are converted to integer type if possible)

pathinfo(path, options) - returns information about a file path.

parameter values:

path : required; specifies the path to be checked;

options : optional; specifies which array element to return; if not specified, it returns all elements; possible values: PATHINFO_DIRNAME - return only dirname, PATHINFO_BASENAME - return only basename, PATHINFO_EXTENSION - return only extension, PATHINFO_FILENAME - return only filename.

pclose(pipe) - closes a pipe opened by popen().

parameter values:

pipe : required; specifies the pipe opened by popen();

popen(command, mode) - opens a pipe.

parameter values:

command : required; specifies the command to execute;

mode: : required; specifies the connection mode; can be "r" (Read only) or "w" (Write only - opens and clears existing file or creates a new file)

readfile(file, include_path, context) - reads a file and writes it to the output buffer.

parameter values:

file : required; specifies the file to read;

include_path : optional; set this parameter to TRUE if you want to search for the file in the include_path (in php.ini) as well;

context : optiona; s`pecifies the context of the file handle; context is a set of options that can modify the behavior of a stream.

readlink(linkpath) - returns the target of a symbolic link.

parameter values:

inkpath : required; specifies the link path to check;

realpath(path) - returns the absolute pathname.

parameter values:

path : required; specifies the path to check;

realpath_cache_get() - returns realpath cache entries.

parameter values: none

realpath_cache_size() - returns realpath cache size.

parameter values: none

rename(old, new, context) - renames a file or directory.

parameter values:

old : required; specifies the file or directory to be renamed ;

new : required; specifies the new name for the file or directory;

context : optional; specifies the context of the file handle; context is a set of options that can modify the behavior of a stream

rewind(file) - rewinds a file pointer.

parameter values:

file : required; specifies the open file;

rmdir(dir, context) - removes an empty directory.

parameter values:

dir : required; specifies the path to the directory to be removed;

context : optional; specifies the context of the file handle; context is a set of options that can modify the behavior of a stream.

set_file_buffer(file, buffer) - alias of stream_set_write_buffer(). Sets the buffer size for write operations on the given file.

parameter values:

file : required; specifies a file pointer;

buffer : required; specifies the number of bytes to buffer./p>

stat(filename) - returns information about a file.

parameter values:

filename : required; specifies the path to the file;

symlink(target, link) - creates a symbolic link

parameter values:

target : required; specifies the target of the link;

link : required; specifies the link name

tempnam(dir, prefix) - creates a unique temporary file.

parameter values:

dir : required; specifies the directory of where to create the temp file;

prefix : required; specifies the start of the filename

tmpfile() - creates a unique temporary file

parameter values: none

touch(filename, time, atime) - sets access and modification time of a file.

parameter values:

filename : required; specifies the file to touch ;

time : optional; sets the touch time; the current system time is set by default;

atime : optional; sets the access time; default is the current system time if no parameters are set, or the same as the time parameter if that parameter is set

umask(mask) - changes file permissions for files.

parameter values:

mask : optional; specifies the new permissions; default is 0777; the mask parameter consists of four numbers: the first number is always zero, the second number specifies permissions for the owner, the third number specifies permissions for the owner's user group, the fourth number specifies permissions for everybody else; possible values (to set multiple permissions, add up the following numbers): 1 = execute permissions, 2 = write permissions, 4 = read permissions;

unlink(filename, context) - deletes a file

parameter values:

filename : required; specifies the path to the file to delete;

context : optional; specifies the context of the file handle; context is a set of options that can modify the behavior of a stream.

PHP file system - functions that are catching

stat(), lstat(), file_exists(), is_writable(), is_readable(),is_executable(), is_file(), is_dir(), is_link(), filectime(), fileatime(), filemtime(), fileinode(), filegroup(), fileowner(), filesize(), filetype(), fileperms().


PHP has several functions for creating, reading, uploading, and editing files.

The "readfile() function" reads a file and writes it to the output buffer.

It returns the number of bytes read on success. The function is useful if all you want to do is open up a file and read its contents.

Syntax: readfile ("file name.ext")

example

AJAX = Asynchronous JavaScript and XML CSS = Cascading Style Sheets HTML = Hyper Text Markup Language PHP = PHP Hypertext Preprocessor SQL = Structured Query Language SVG = Scalable Vector Graphics XML = EXtensible Markup Language 240
code:
                <?php
                    echo readfile("webdictionary.txt");
                ?>                
            

A better method to open files is with the "fopen() function".

This gives you more options than the readfile() function.

The fopen() function is also used to create a file. If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing (w) or appending (a).

Syntax: fopen(name of file, mode)

modes:

r : open a file for read only : file pointer starts at the beginning of the file.

w : open a file for write only : erases the contents of the file or creates a new file if it doesn't exist; file pointer starts at the beginning of the file.

a : open a file for write only :the existing data in file is preserved; file pointer starts at the end of the file. creates a new file if the file doesn't exist.

x : creates a new file for write only : returns FALSE and an error if file already exists.

r+ : open a file for read/write : file pointer starts at the beginning of the file.

w+ : open a file for read/write : erases the contents of the file or creates a new file if it doesn't exist; file pointer starts at the beginning of the file.

a+ : open a file for read/write : the existing data in file is preserved; file pointer starts at the end of the file; creates a new file if the file doesn't exist.

x+ : creates a new file for read/write : returns FALSE and an error if file already exists.

example

AJAX = Asynchronous JavaScript and XML CSS = Cascading Style Sheets HTML = Hyper Text Markup Language PHP = PHP Hypertext Preprocessor SQL = Structured Query Language SVG = Scalable Vector Graphics XML = EXtensible Markup Language
code:
                <?php
                    $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
                    echo fread($myfile,filesize("webdictionary.txt"));
                    fclose($myfile);
                ?>        
            

The "fread() function" reads from an "open file".

The first parameter of fread() contains the name of the file to read from and the second parameter specifies the maximum number of bytes to read.

Syntax: fread($myfile,filesize("xxx"));

example

code:
                
            

The "fclose() function" is used to close an open file.

The fclose() requires the name of the file (or a variable that holds the filename) we want to close.

Syntax: fclose($myfile);

example

code:
                
            

The "fgets() function" is used to read a single line from a file.

Syntax: fgets($myfile);

After a call to the fgets() function, the file pointer has moved to the next line.

example

AJAX = Asynchronous JavaScript and XML
code:
                <?php
                    $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
                    echo fgets($myfile);
                    fclose($myfile);
                ?>
            

The "feof() function" checks if the "end-of-file" (EOF) has been reached.

The feof() function is useful for looping through data of unknown length.

Syntax: feof($myfile)

example

AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language


code:
                <?php
                    $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
                    // Output one line until end-of-file
                    while(!feof($myfile)) {
                    echo fgets($myfile) . "<br>";
                    }
                    fclose($myfile);
                ?>
            

The "fgetc() function" is used to read a single character from a file.

syntax: fgetc($myfile)

After a call to the fgetc() function, the file pointer has moved to the next character.

example

AJAX = Asynchronous JavaScript and XML CSS = Cascading Style Sheets HTML = Hyper Text Markup Language PHP = PHP Hypertext Preprocessor SQL = Structured Query Language SVG = Scalable Vector Graphics XML = EXtensible Markup Language
code:
            class="spec">
                <?php
                    $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
                    // Output one character until end-of-file
                    while(!feof($myfile)) {
                    echo fgetc($myfile);
                    }
                    fclose($myfile);
                ?>
            

The "fwrite() function" is used to write to a file.

The first parameter of fwrite() contains the name of the file to write to and the second parameter is the string to be written.
When we open an existing file for writing, all the existing data will be ERASED and we start with an empty file.

Syntax: fwrite($myfile, $txt);

example

code:
                <?php
                    $myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
                    $txt = "John Doe\n";
                    fwrite($myfile, $txt);
                    $txt = "Jane Doe\n";
                    fwrite($myfile, $txt);
                    fclose($myfile);
                ?>
            

In the example below we open our existing file "newfile.txt", and write some new data into it.

example

code:
                <?php
                    $myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
                    $txt = "Mickey Mouse\n";
                    fwrite($myfile, $txt);
                    $txt = "Minnie Mouse\n";
                    fwrite($myfile, $txt);
                    fclose($myfile);
                ?>
            

If we now open the "newfile.txt" file, both John and Jane have vanished, and only the data we just wrote is present.

You can append data to a file by using the "a" mode. The "a" mode appends text to the end of the file, while the "w" mode overrides (and erases) the old content of the file.

example

code:
                <?php
                    $myfile = fopen("newfile.txt", "a") or die("Unable to open file!");
                    $txt = "Donald Duck\n";
                    fwrite($myfile, $txt);
                    $txt = "Goofy Goof\n";
                    fwrite($myfile, $txt);
                    fclose($myfile);
                ?>
            

If we now open the "newfile.txt" file, we will see that Donald Duck and Goofy Goof is appended to the end of the file.